package com.ubao.location;

import com.google.android.maps.GeoPoint;
import com.ubao.util.log.Logger;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class LocationHandler {
	public  GeoPoint point;
	public  String longtitude;
	public  String latitude;
	public  Location tmpLocation;
	private final static int INTERVAL = 60000;
	Context mContext;
	LocationManager locationManager;
	LocationListener gpsLocationListener;
	LocationListener networkLocationListener;
	public LocationHandler(Context ctx){
		mContext = ctx;
		init();
	}
	private void init() {
		locationManager  = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
		gpsLocationListener = new LocationListener() {
		    public void onLocationChanged(Location location) {
		      // Called when a new location is found by the network location provider.
		      makeUseOfNewLocation(location,true);
		      Logger.d("gpschanged");
		    }
			public void onStatusChanged(String provider, int status, Bundle extras) {
				Logger.d("gpsonStatusChanged");
			}

		    public void onProviderEnabled(String provider) {
		    	Logger.d("gpsonProviderEnabled");
		    }

		    public void onProviderDisabled(String provider) {
		    	Logger.d("gpsonProviderDisabled");
		    }
		  };
		  
		  networkLocationListener = new LocationListener() {
			    public void onLocationChanged(Location location) {
			      // Called when a new location is found by the network location provider.
			      makeUseOfNewLocation(location,false);
			      Logger.d("networkchanged");
			    }
				public void onStatusChanged(String provider, int status, Bundle extras) {
					Logger.d("networkonStatusChanged");
				}

			    public void onProviderEnabled(String provider) {
			    	Logger.d("networkonProviderEnabled");
			    }

			    public void onProviderDisabled(String provider) {
			    	Logger.d("networkonProviderDisabled");
			    }
			  };
			  //handler.sendEmptyMessage(0);
	}
	
	
	
	private void makeUseOfNewLocation(Location location,boolean isGps) {
		if(isBetterLocation(location, tmpLocation,isGps)){
			tmpLocation = location;
			longtitude = String.valueOf(location.getLongitude());
			latitude = String.valueOf(location.getLatitude());
			point = new GeoPoint((int)(location.getLatitude()*1E6), (int)(location.getLongitude()*1E6));
			Logger.d("  " + point);
		}
	}
	
	Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			Logger.d("gogogo");
			super.handleMessage(msg);
			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, INTERVAL, 0, gpsLocationListener);
			locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, INTERVAL, 0, networkLocationListener);
		}
		
	};
	
	
	protected boolean isBetterLocation(Location location, Location currentBestLocation,boolean isGps) {
	    if (currentBestLocation == null||isGps) {
	        // A new location is always better than no location
	        return true;
	    }

	    // Check whether the new location fix is newer or older
	    long timeDelta = location.getTime() - currentBestLocation.getTime();
	    boolean isSignificantlyNewer = timeDelta > INTERVAL;
	    boolean isSignificantlyOlder = timeDelta < -INTERVAL;
	    boolean isNewer = timeDelta > 0;

	    // If it's been more than two minutes since the current location, use the new location
	    // because the user has likely moved
	    if (isSignificantlyNewer) {
	        return true;
	    // If the new location is more than two minutes older, it must be worse
	    } else if (isSignificantlyOlder) {
	        return false;
	    }

	    // Check whether the new location fix is more or less accurate
	    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
	    boolean isLessAccurate = accuracyDelta > 0;
	    boolean isMoreAccurate = accuracyDelta < 0;
	    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

	    // Check if the old and new location are from the same provider
	    boolean isFromSameProvider = isSameProvider(location.getProvider(),
	            currentBestLocation.getProvider());

	    // Determine location quality using a combination of timeliness and accuracy
	    if (isMoreAccurate) {
	        return true;
	    } else if (isNewer && !isLessAccurate) {
	        return true;
	    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
	        return true;
	    }
	    return false;
	}

	/** Checks whether two providers are the same */
	private boolean isSameProvider(String provider1, String provider2) {
	    if (provider1 == null) {
	      return provider2 == null;
	    }
	    return provider1.equals(provider2);
	}
	
	
	public void exit(){
		locationManager.removeUpdates(gpsLocationListener);
		locationManager.removeUpdates(networkLocationListener);
	}
	
	public void locate(){
		handler.sendEmptyMessage(0);
	}
	
	public boolean checkIsEnableLocation(){
		if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)&&!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
			return false;
		}
		return true;
	}
}
